/**
 * @Author: Bobby
 * @Date: 2022-02-15 13:14:24
 * @LastEditTime: 2022-03-24 10:37:07
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\ve\eventTask\actions\requestApi.js
 * @CIMC-V2
 */
import { gp } from '@vui'
import isEmpty from 'lodash/isEmpty'
import cloneDeep from 'lodash/cloneDeep'
import isArray from 'lodash/isArray'
import merge from 'lodash/merge'
import isPlainObject from 'lodash/isPlainObject'
import trim from 'lodash/trim'
import { getModelInfo } from '@ve/utils/getModelInfo'
import { GFCD } from '@/utils/utils'
// import { decryptd } from '@/utils/tools'
import request from '@/utils/request'
import { processingConstant, replaseRegVariable, getModelByModelTree } from '@ve/utils/utils'
import { ElMessage } from 'element-plus'
import { translateTitle } from '@/utils/i18n'

// let requestOpen = false
//必须带done回调 执行完成调用
export default function requestApi({ vm, action, callbackData, done }) {
  let { type, useCallbackData, callbackDataKey, api, method, getDataKey, data, openMessage } = action.extension.requestConfig.value
  let _additionalData = {} //附加数据 比如来自组件的自定义参数
  let _data = {}
  let _modelInfo = {}
  let _selfRef = null
  // type=1 以自己配置为主
  if (type == 1) {
    data.forEach((v) => {
      if (isPlainObject(v.value)) {
        const moduleId = v.value.sourceId.value.source[0] || ''
        // 如果参数值是对象的话 则代表是复杂参数 则需要找到对应模块取值
        if (!moduleId) return
        // 获取复杂参数值
        _data[v.key] = getComplexParam(vm, v, moduleId)
      } else {
        _data[v.key] = processingConstant(vm, v.value)
      }
    })
    // 回调数据
    if (useCallbackData && !isEmpty(callbackData)) {
      if (isEmpty(callbackDataKey)) {
        if (isArray(callbackData)) {
          _data = callbackData.map((item) => {
            // 解析配置参数的变量
            data.forEach((v) => {
              let itemVal = v.value
              if (/{[^#{]+}/g.test(v.value)) {
                // itemVal = item[trim(v.value.substring(2, v.value.length - 1))]
                itemVal = replaseRegVariable(itemVal, item)
              }
              if (!isPlainObject(itemVal)) {
                _data[v.key] = processingConstant(vm, itemVal)
              }
              if (isPlainObject(itemVal)) {
                const moduleId = v.value.sourceId.value.source[0] || ''
                // 如果参数值是对象的话 则代表是复杂参数 则需要找到对应模块取值
                if (!moduleId) return
                // 获取复杂参数值
                _data[v.key] = getComplexParam(vm, v, moduleId)
              }
            })
            return merge(item, _data)
          })
        } else {
          // 解析配置参数的变量
          data.forEach((v) => {
            let itemVal = v.value
            if (/{[^#{]+}/g.test(v.value)) {
              itemVal = replaseRegVariable(itemVal, callbackData)
            }
            _data[v.key] = processingConstant(vm, itemVal)
            if (isPlainObject(itemVal)) {
              const moduleId = v.value.sourceId.value.source[0] || ''
              // 如果参数值是对象的话 则代表是复杂参数 则需要找到对应模块取值
              if (!moduleId) return
              // 获取复杂参数值
              _data[v.key] = getComplexParam(vm, v, moduleId)
            }
          })
          _data = {
            ...cloneDeep(callbackData),
            ..._data,
          }
        }
      } else {
        _data[callbackDataKey] = callbackData
      }
    }
  }
  //type=2 以组件配置为主
  if (type == 2) {
    //通过组件id找到模块信息
    let _componentId = action.extension.requestConfig.value.component[0]
    if (!_componentId) {
      ElMessage({
        showClose: true,
        message: translateTitle('Ve.eventTask.调用接口的组件'),
        type: 'error',
      })
    }
    if (
      _componentId.indexOf('uiTree') > -1 ||
      _componentId.indexOf('uiSelect') > -1 ||
      _componentId.indexOf('uiDynamicTable') > -1 ||
      _componentId.indexOf('uiFlowChart') > -1 ||
      _componentId.indexOf('uiTransfer') > -1 ||
      _componentId.indexOf('uiList') > -1 ||
      _componentId.indexOf('uiCheckbox') > -1
    ) {
      // 如果是树形组件或者下拉选择组件 则调用组件自身的请求方法 (或者是动态表格组件、流程图组件)
      let _module = vm.vuiComponents[_componentId]
      if (_module) {
        _module.self &&
          _module.self.$requestData((res) => {
            done(null, res)
          })
      }
      return
    }
    _modelInfo = getModelInfo(vm, _componentId)
    if (['uiTable', 'uiCirculationForm', 'uiDynamicForm', 'uiDynamicFormLot', 'uiUpload'].includes(_modelInfo.type)) {
      _selfRef = vm.vuiComponents && vm.vuiComponents[_modelInfo._id]
      if (_selfRef) {
        _selfRef.self.$data.loading = true
        _additionalData = _selfRef.self.$getRequestData()
        if (_modelInfo.extension.batchAttribute && _modelInfo.extension.batchAttribute.value.open) {
          // 如果组件配置了动态表头（此时一定是表格组件） 则调用请求表头的接口
          _selfRef.self.batchAttributeInit && _selfRef.self.batchAttributeInit()
        }
        // 缓存表格选中数据
        if (_modelInfo.type == 'uiTable' && _selfRef.self.getKeppSelect) {
          _selfRef.self.saveSelectedRows && _selfRef.self.saveSelectedRows()
        }
      }
    }
    //中途删除组件后需要重新选择
    if (_componentId.length <= 0 || isEmpty(_modelInfo)) {
      done(null, {})
      return
    }
    //获取模块配置接口信息
    if (!_modelInfo.extension.api.value) {
      ElMessage({
        showClose: true,
        message: translateTitle('Ve.eventTask.组件未配置接口'),
        type: 'error',
      })
      _selfRef.self.$data.loading = false
      return
    }
    api = _modelInfo.extension.api.value
    method = _modelInfo.extension.method.value
    if (_modelInfo.type == 'uiUpload') {
      method = _modelInfo.extension.echoMethod.value
    }
    getDataKey = _modelInfo.extension.getDataKey ? _modelInfo.extension.getDataKey.value : ''
    // console.log('_modelInfo', cloneDeep(_modelInfo))
    if (_modelInfo.type == 'uiCirculationForm') {
      _additionalData = $getRequestData(vm, _modelInfo.extension.requestData)
    }
    if (String(_modelInfo.type).indexOf('uiDynamicForm') !== -1) {
      for (let key in _additionalData) {
        !_modelInfo.data.formData[key] && (_modelInfo.data.formData[key] = _additionalData[key])
      }
    }
    if (_modelInfo.data && _modelInfo.data.formData) {
      _data = {
        ..._modelInfo.data.formData,
        ..._additionalData,
        // ..._data_obj,
        ...{ '#LIMIT#': 1 },
      }
      //二次请求默认到一页
      _modelInfo.data.formData = _data
    }
  }
  //发起请求
  request({
    url: GFCD('dams', 'domain') + api,
    method: 'post',
    data: {
      data: JSON.stringify(_data),
      method: method,
    },
    notOpenMessage: !openMessage,
    responseType: _data[0]?.flag ? 'blob' : 'json',
  })
    .then((res) => {
      //解密
      console.log(type, res, _modelInfo, _data)
      if (type === 2) {
        if (_modelInfo.type == 'uiDynamicFormLot') {
          // 批次属性组件赋默认值
          let _componentId = action.extension.requestConfig.value.component[0]
          vm.vuiComponents[_componentId] && vm.vuiComponents[_componentId].self.assignDefaultValue()
        }
        _modelInfo.data.requestData = isEmpty(getDataKey) ? res.data : isArray(res.data) ? res.data[0] : res.data[getDataKey]
        if (_modelInfo.type == 'uiTable' && _selfRef) {
          _selfRef.self.$data.loading = false
          // 如果有配置保留选中则选中之前的数据
          if (_selfRef.self.getKeppSelect) {
            vm.$nextTick(() => {
              _selfRef.self.setkeepSelectData && _selfRef.self.setkeepSelectData()
            })
          }
        }
      } else {
        // let list = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
        // if (list) module.data.requestData.data = dataSourceMatching(module, list.data)

        if (openMessage && res.msg) {
          gp.$baseMessage(res.msg, res.code == '00000' ? 'success' : 'error')
        }
        //配置的文件下载
        if (_data[0]?.flag) {
          if (res.size) {
            // 针对下载请求返回失败之后的处理等
            // 将blob转为json
            const reader = new FileReader()
            let parseObj = null
            reader.readAsText(res, 'utf-8')
            reader.onload = () => {
              parseObj = JSON.parse(reader.result)
              console.log(parseObj)
              gp.$baseMessage(parseObj.msg, 'error')
            }
          } else {
            let blob = new Blob([res.data])
            console.log(blob)
            let downloadElement = document.createElement('a')
            let href = window.URL.createObjectURL(blob)
            downloadElement.href = href
            downloadElement.download = decodeURI(res.disposition.split("''")[res.disposition.split("''").length - 1])
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href)
          }
        }
      }

      // 存储动作数据
      vm.$store.dispatch('actionDatas/setActionsData', {
        moduleId: vm.info._id,
        actionId: action._id,
        actionData: res,
      })
      // 将下一次动作执行放到页面更新之后 防止获取触发表格双击时获取表格数据失败
      vm.$nextTick(() => {
        done(null, res)
      })
    })
    .catch((error) => {
      if (type === 2) {
        if (_modelInfo.type == 'uiTable' && _selfRef) {
          _selfRef.self.$data.loading = false
        } else if (_modelInfo.type == 'uiDynamicFormLot') {
          // 批次属性组件赋默认值
          let _componentId = action.extension.requestConfig.value.component[0]
          vm.vuiComponents[_componentId] && vm.vuiComponents[_componentId].self.assignDefaultValue()
        }
        _modelInfo.data && (_modelInfo.data.requestData = [])
      }
      // 存储动作数据
      vm.$store.dispatch('actionDatas/setActionsData', {
        moduleId: vm.info._id,
        actionId: action._id,
        actionData: error,
      })
      done(null, error)
    })
}

function $getRequestData(vm, data) {
  let _data = {}
  if (data && isArray(data.value)) {
    data.value.forEach((item) => {
      console.log(item.value)
      _data[item.key] = processingConstant(vm, item.value)
    })
  }
  return _data
}

// 获取复杂参数组件值
function getComplexParam(vm, v, moduleId) {
  let _value = ''
  const modulelObj = getModelByModelTree(moduleId, vm.$store.getters['preview/getNowPageData'])
  if (modulelObj.type === 1 || modulelObj.type === 2) {
    // 如果绑定的是页面类型 则获取页面的 requestData
    _value = modulelObj?.data?.requestData
    if (v.value.getDataKey) {
      // 如果有获取数据key 则根据获取数据key筛选数据
      const getDataKeyList = v.value.getDataKey.split(',')
      let _dataObj = {}
      getDataKeyList.map((item) => {
        item = trim(item)
        _dataObj[item] = _value[item]
      })
      _value = _dataObj
    }
  } else if (modulelObj.type === 'uiTable') {
    // 如果选择的是表格组件 则获取表格选中数据
    let _table = vm.vuiComponents[moduleId]
    if (!_table) return
    if (_table.self.hasCheckboxOrRadio == 'checkbox') {
      _value = _table.ref.getCheckboxRecords()
      if (v.value.getDataRow) {
        // 如果有获取数据行 则根据获取数据行筛选数据
        _value = _value[v.value.getDataRow]
      }
    } else {
      _value = _table.ref.getRadioRecord()
    }
  } else if (modulelObj.type == 'uiCirculationForm') {
    _value = modulelObj?.data.requestListData
  } else {
    // 其余情况下皆获取组件的formData
    _value = modulelObj?.data?.formData
    if (v.value.getDataKey) {
      // 如果有获取数据key 则根据获取数据key筛选数据
      const getDataKeyList = v.value.getDataKey.split(',')
      let _dataObj = {}
      getDataKeyList.map((item) => {
        item = trim(item)
        _dataObj[item] = _value[item]
      })
      _value = _dataObj
    }
  }
  return _value
}
